// ************************************************************
// Copyright © 2021
// File Name: mem.go
// Author:
// Email:
// Created: 2021-12-27 09:15:05 (CST)
// Last Update:
//          By:
// Description:
// ************************************************************
package data

import (
	"errors"
	"sync"
)

type BookPO struct {
	Id      string
	Name    string
	Authors []string
	Press   string
}

var (
	ErrNotFound = errors.New("Not found")
	ErrExist    = errors.New("Exist")
)

type MemStore struct {
	sync.RWMutex
	books map[string]*BookPO
}

// 书籍信息存放在内存中，当前不使用数据库
func NewMemStore() *MemStore {
	return &MemStore{
		books: make(map[string]*BookPO),
	}
}

func (ms *MemStore) Add(book *BookPO) error {
	ms.Lock()
	defer ms.Unlock()
	if _, ok := ms.books[book.Id]; ok {
		return ErrExist
	}
	nBook := *book
	ms.books[book.Id] = &nBook
	return nil
}

func (ms *MemStore) Get(id string) (BookPO, error) {
	ms.Lock()
	defer ms.Unlock()
	bookPO, ok := ms.books[id]
	if !ok {
		return BookPO{}, ErrNotFound
	}
	return *bookPO, nil
}
